package com.wx.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.eova.common.Easy;
import com.eova.common.utils.xx;
import com.eova.core.IndexController;
import com.eova.interceptor.AuthInterceptor;
import com.eova.interceptor.LoginInterceptor;
import com.jfinal.aop.Clear;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.wx.model.PartyInfo;
import com.wx.model.PartyPrizeDetail;
import com.wx.model.PartyUser;
import com.wx.service.MarketingService;
import com.wx.service.UserIndexService;
import com.wx.sql.MarketingSql;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.json.JSONUtil;
import com.xiaoleilu.hutool.util.StrUtil;

@Clear({LoginInterceptor.class,AuthInterceptor.class})
public class UserIndexController extends IndexController{
	
	
	static final MarketingService marketingService = MarketingService.me;  
	static final UserIndexService userIndexService = UserIndexService.me;  
	/**
	 * 
	 */
	@Override
	public void index(){
//		String url = "http://" + this.getRequest().getServerName() //服务器地址  
//		        + ":"   
//		        + this.getRequest().getServerPort()           //端口号  
//		        + this.getRequest().getContextPath()      //项目名称  
//		        + this.getRequest().getServletPath()      //请求页面或其他地址  
//		    + "?" + (this.getRequest().getQueryString()); //参数 
//				renderText(url);
		//获取用户基本信息
		String area_id = getPara("area_id");
		String key = getPara("key");
		String tel = getPara("tel");
		int party_id = getParaToInt("party_id",1);
		PartyInfo party = PartyInfo.dao.findById(party_id);
		String user_id = getPara("user_id");
		try{
//			//根据key获取user_id 
//			String actionUrl = xx.getConfig(area_id+"URL")+"ddd.do";
//			
//			String userid = HttpUtil.get(actionUrl);
			
			//判断用户是否存在
			PartyUser user = PartyUser.dao.getUserByCode(user_id);
//			System.out.println(user.toString());
			if(user!=null){
				if(!key.equals(user.getRequestKey())){
					user.setRequestKey(key);
					user.update(); 
				}
			}else{
				user = new PartyUser();
				user.setUserName(user_id);
				user.setPhone(tel);
				user.setUserCode(user_id);
				user.setCreateDate(new Date());
				user.setUserSource(area_id);
				user.setUserType(1);
				user.setRequestKey(key);
				user.save();
			}
			if(party.getReduceType()==0){
				//抽奖次数
				//获取抽奖次数
				Ret ret = userIndexService.getNumberOfAwards(user, party_id);
				int i = ret.getInt("CJCS");
				setAttr("CJCS", i);
			}else{
				//积分
				//获取积分信息
				Map paramMap=new HashMap<>();
				paramMap.put("key", user.getRequestKey());
				paramMap.put("points", 0 );
				//获取请求URL
				String actionUrl = xx.getConfig(user.getUserSource()+"URL")+"api.php?controller=jackpot&action=changeOpportunityForLottery";
				String response = HttpUtil.get(actionUrl, paramMap);
				System.out.println("======="+response);
				Map map = JSONUtil.parseObj(response);
				int score = 0;
				if(map.get("errcode")!=null&&(int)map.get("errcode")==0){
					//获得积分
					score = Integer.valueOf((String) ((Map)map.get("info")).get("month_score"));
				}else{
					score = 0;
				}
				setAttr("REDUCENUM", party.getReduceNum());
				setAttr("SCORE", score);
			}
			//跳转页面
			List<PartyPrizeDetail> prizeList = PartyPrizeDetail.dao.find(MarketingSql.getAwardDetail(party_id));
//			setAttr("CJCS",1);
			
			System.out.println("======="+user.getUserCode());
			//获取活动规则
			String rule = "";
			if(!StrUtil.isBlank(party.getPartyRule())){
				rule = party.getPartyRule();
			}
			setAttr("PARTY_RULE",rule);
			setAttr("USER", user);
			setAttr("PARTY_ID", party_id);
			setAttr("PRIZELIST",prizeList);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			
		}
		if(party!=null){
			renderTemplate(party.getTemplateUrl());
		}else{
			renderTemplate("/wx/choujianng/award/index.html");
		}
		
//		renderTemplate("/wx/cj/choujiang2/index.html");
//		renderTemplate("/wx/choujianng/index.html");
	}
	/**
	 * @Description: 获得次数
	 * @param    
	 * @return void  
	 * @throws
	 * @author liuxin
	 * @date 2018年5月21日
	 */
	public void getNumberOfAwards(){
		Easy easy = new Easy();
		String msg = "";
		if( getRequest().getParameter("USER_SOURCE") == null){
			msg += "用户来源为空;";
		}
		if(getRequest().getParameter("USER_TYPE") == null){
			msg += "用户类型为空;";
		}
		if(getRequest().getParameter("USER_CODE") == null){
			msg += "用户编码为空;";
		}
		if(getRequest().getParameter("LOGIN_NUM") == null){
			msg += "登录次数为空;";
		}
		if(getRequest().getParameter("ORDER_NUM") == null){
			msg += "下单次数为空;";
		}
		if(getRequest().getParameter("REPEAT_NUM") == null){
			msg += "转发次数为空;";
		}
		if(getRequest().getParameter("PARTY_ID") == null){
			msg += "活动ID为空;";
		}
		if(!"".equals(msg)){
		
			easy.setMsg(msg);
			easy.setSuccess(true);
		}
		try {
			Map<String, Object> map = new HashMap<String, Object>(7);
			map.put("USER_SOURCE", getRequest().getParameter("USER_SOURCE"));
			map.put("USER_TYPE", getRequest().getParameter("USER_TYPE"));
			map.put("USER_CODE", getRequest().getParameter("USER_CODE"));
			map.put("LOGIN_NUM", getRequest().getParameter("LOGIN_NUM"));
			map.put("ORDER_NUM",getRequest().getParameter("ORDER_NUM"));
			map.put("REPEAT_NUM", getRequest().getParameter("REPEAT_NUM"));
			map.put("PARTY_ID", getRequest().getParameter("PARTY_ID"));
			renderJson(marketingService.getNumberOfAwards(map));
			setAttr("USER_CODE", map.get("USER_CODE"));
			setAttr("PARTY_ID", map.get("PARTY_ID"));
			renderTemplate("/wx/choujianng/index.html");
		} catch (Exception e) {
			e.printStackTrace();
		}
	
	}
	
	/**
	 * @Description: 获取用户所得奖励
	 * @param    
	 * @return void  
	 * @throws
	 * @author liuxin
	 * @date 2018年5月21日
	 */
	public void getAwards(){
		Easy easy = new Easy();
		String msg = "";
		if( getRequest().getParameter("USER_CODE") == null){
			msg += "用户编码为空;";
		}
		if(getRequest().getParameter("PARTY_ID") == null){
			msg += "活动ID为空;";
		}
		if(!"".equals(msg)){
		
			easy.setMsg(msg);
			easy.setSuccess(true);
		}else{
			try {
				Map<String, Object> map = new HashMap<String, Object>(2);
				map.put("USER_CODE", getRequest().getParameter("USER_CODE"));
				map.put("PARTY_ID", getRequest().getParameter("PARTY_ID"));
				easy = marketingService.getAReward(map);
			} catch (Exception e) {
				e.printStackTrace();
			}
		
		}
		renderJson(easy);
	}
	
	/**
	 * @Description: 获取该活动参与抽奖的奖励
	 * @param    
	 * @return void  
	 * @throws
	 * @author liuxin
	 * @date 2018年5月21日
	 */
	public void getAwardDetail(){
		Easy easy = new Easy();
		String msg = "";
		if(getRequest().getParameter("PARTY_ID") == null){
			msg += "活动ID为空;";
		}
		if(!"".equals(msg)){
			easy.setMsg(msg);
			easy.setSuccess(true);
		}else{
			List<PartyPrizeDetail> prizeList = PartyPrizeDetail.dao.find(MarketingSql.getAwardDetail(Integer.parseInt(getRequest().getParameter("PARTY_ID"))));
			easy.setMsg("SUCCESS");
			easy.setData(prizeList);
			easy.setSuccess(true);
		}
		renderJson(easy);
	}
	
	public void myAward(){
		//获取用户基本信息
		String party_id = getPara("party_id");
		String user_id = getPara("user_id");
		List<Record> partyPrizeRecords = Db.find(MarketingSql.getAwardRecord(),party_id,user_id);//Db.find(MarketingSql.getAwardRecord(),party_id,user_id);
		setAttr("partyPrizeRecords", JSON.toJSON(partyPrizeRecords));
		renderTemplate("/wx/choujianng/award_guajiang1/awardList.html");
	}
}
